<?php

namespace App\Models\Logs;

use App\Library\ClientIp;
use App\Traits\DateTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Jenssegers\Agent\Agent;
use Illuminate\Database\Eloquent\Model;

class AccessLog extends Model
{
    use DateTrait;
    protected $table = 'access_log';
    protected $fillable = ['path', 'method', 'input', 'platform', 'browser', 'ip', 'ip_address', 'header'];

    /**
     * @param Request $request
     */
    public static function CreateAccessLog(Request $request)
    {
        try {
            DB::transaction(function () use ($request) {
                $agent = new Agent;
                $ip = getClientIp();
                static::query()->create([
                    "path"          => substr($request->path(), 0, 255),
                    "method"        => $request->method(),
                    "input"         => json_encode($request->input()),
                    "ip"            => $ip,
                    "ip_address"    => ClientIp::getLocation($ip)["region"],
                    "platform"      => $agent->platform(),
                    "browser"       => $agent->browser(),
                    "header"        => json_encode($request->header()),
                ]);
            });
        } catch (\Exception $e) {
            report($e);
        }
    }
}
